'use strict';

/**
 * 字典项控制器
 */
const Controller = require('egg').Controller;

class DictItemController extends Controller {
  /**
   * 创建字典项
   * @return {Promise<void>}
   */
  async create() {
    const { ctx, service } = this;
    const dictItemData = ctx.request.body;
    const result = await service.dictItem.create(dictItemData);
    ctx.success(result);
  }

  /**
   * 查询字典项列表
   * @return {Promise<void>}
   */
  async index() {
    const { ctx, service } = this;
    const { page = 1, pageSize = 10, ...query } = ctx.query;
    const result = await service.dictItem.list(query, Number(page), Number(pageSize));
    ctx.success(result);
  }

  /**
   * 查询单个字典项
   * @return {Promise<void>}
   */
  async show() {
    const { ctx, service } = this;
    const { id } = ctx.params;
    const result = await service.dictItem.findById(id);
    ctx.success(result);
  }

  /**
   * 更新字典项
   * @return {Promise<void>}
   */
  async update() {
    const { ctx, service } = this;
    const { id } = ctx.params;
    const dictItemData = ctx.request.body;
    const result = await service.dictItem.update(id, dictItemData);
    ctx.success(result);
  }

  /**
   * 删除字典项
   * @return {Promise<void>}
   */
  async destroy() {
    const { ctx, service } = this;
    const { id } = ctx.params;
    await service.dictItem.destroy(id);
    ctx.success(null, '删除成功');
  }

  /**
   * 更新字典项状态
   * @return {Promise<void>}
   */
  async updateStatus() {
    const { ctx, service } = this;
    const { id, status } = ctx.request.body;
    await service.dictItem.updateStatus(id, status);
    ctx.success(null, '状态更新成功');
  }

  /**
   * 根据字典类型编码获取字典项
   * @return {Promise<void>}
   */
  async getByDictTypeCode() {
    const { ctx, service } = this;
    const { code, status } = ctx.query;
    const result = await service.dictItem.getByDictTypeCode(code, status);
    ctx.success(result);
  }

  /**
   * 批量创建或更新字典项
   * @return {Promise<void>}
   */
  async batchCreateOrUpdate() {
    const { ctx, service } = this;
    const { dictTypeId, items } = ctx.request.body;
    await service.dictItem.batchCreateOrUpdate(dictTypeId, items);
    ctx.success(null, '批量操作成功');
  }
}

module.exports = DictItemController;
